package cron

import (
	"bigdevops/src/common"
	"context"
	"encoding/json"
	"go.uber.org/zap"
)

type RobotTenantAccessTokenReq struct {
	AppId     string `json:"app_id"`
	AppSecret string `json:"app_secret"`
}

type RobotTenantAccessTokenRes struct {
	Code              int    `json:"code"`
	Expire            int    `json:"expire"`
	Msg               string `json:"msg"`
	TenantAccessToken string `json:"tenant_access_token"`
}

func (ac *AlertCache) RefreshSiLiaoRebotToken(ctx context.Context) {

	//	    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
	//    data = {
	//        "app_id": "cli_a5c4425d311e900b",
	//        "app_secret": "4gLsIW6Vt3yQXpaZfHrALemd8GKPUUzx"
	//    }
	//    res = requests.post(url, json=data)
	//    print(res.status_code)
	//    print(res.json())
	//    return res.json().get("tenant_access_token")
	data := RobotTenantAccessTokenReq{
		AppId:     ac.Sc.ImFeishuC.SiLiaoRobotAppId,
		AppSecret: ac.Sc.ImFeishuC.SiLiaoRobotAppSecret,
	}
	emptyMap := map[string]string{}
	jsonStr, _ := json.Marshal(data)
	bodyBytes, err := common.PostWithJsonString(
		ac.Sc.Logger,
		"RefreshSiLiaoRebotToken",
		ac.Sc.ImFeishuC.RequestTimeoutSeconds,
		ac.Sc.ImFeishuC.TenantAccessTokenApi,
		string(jsonStr), emptyMap, emptyMap)
	if err != nil {
		return
	}
	var res *RobotTenantAccessTokenRes
	err = json.Unmarshal(bodyBytes, &res)
	if err != nil {
		ac.Sc.Logger.Error("获取token解析json失败",
			zap.Error(err),
			zap.Any("AppId", ac.Sc.ImFeishuC.SiLiaoRobotAppId),
		)
		return
	}
	ac.SiLiaoRobotTokenLock.Lock()
	ac.SiLiaoRobotToken = res.TenantAccessToken
	ac.SiLiaoRobotTokenLock.Unlock()

}

func (ac *AlertCache) GetSiLiaoRobotToken() string {
	ac.SiLiaoRobotTokenLock.RLock()
	defer ac.SiLiaoRobotTokenLock.RUnlock()
	return ac.SiLiaoRobotToken
}
